package cahce;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

import entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class CacheService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String USER_CACHE_PREFIX = "user:";
    private static final String ORDER_CACHE_PREFIX = "order:";

    public User getUserCache(Long userId) {
        String key = USER_CACHE_PREFIX + userId;
        User user = (User) redisTemplate.opsForValue().get(userId);
        if (user == null) {
            user = getUserFromDb(userId);
            redisTemplate.opsForValue().set(key, user, 1, TimeUnit.HOURS);
        }
        return user;
    }

    private User getUserFromDb(Long userId) {
        User user = new User();
        user.setId(0L);
        user.setUserName("");
        user.setPassword(0L);
        user.setCreateTime(LocalDateTime.now());
        return user;
    }
}
